import cloud from '@lafjs/cloud'
let dbName = "admin-config"
const db = cloud.database();

export default async function (ctx: FunctionContext) {
  console.log("ctx.body", ctx.body)
  switch (ctx.body.type) {
    case "update":
      return updateFunc(ctx.body.data)
      break;
    case "details":
      return seeDetailsFunc()
      break;
    default:
      break;
  }
}

let updateFunc = async (dataJson) => {
  let { data } = await db.collection(dbName).get();
  if (data.length) {
    await cloud.utils.ossDel('file', dataJson.oldDownUrl) //删除旧文件
    let query = { ...dataJson }
    delete query.oldDownUrl
    await cloud.nw.db.update({
      dbName, dataJson: query,
      whereJson: {
        _id: data[0]._id,
      },
    });
  } else {
    await cloud.nw.db.add({
      dbName, dataJson
    });
  }
  return cloud.utils.requestReturn({ data: "" })
}

let seeDetailsFunc = async () => {
  let { data } = await db.collection(dbName).get();
  return cloud.utils.requestReturn({ data: data[0] })
}
